/* eslint-disable react/jsx-no-bind */
import React from 'react';
import { Action, useFormatMessage, axios } from '@choerodon/master';
import { Table, Tooltip, Modal } from 'choerodon-ui/pro';
import { get } from '@choerodon/inject';
import map from 'lodash/map';
import { TimePopover } from '@choerodon/components';
import { observer } from 'mobx-react-lite';
import { environmentApiApi } from '@/api';
import { useREStore } from '../../../../stores';
import { useResourceStore } from '@/routes/resource/stores';
import { TableQueryBarType } from '@/interface';

const configTable = get('configuration.environment.permissionAssign:table');

const { Column } = Table;
const Permissions = () => {
  const {
    intlPrefix,
    formatMessage,
    AppState: {
      currentMenuType: {
        id: projectId,
      },
    },
    resourceStore: {
      getSelectedMenu: {
        id: envId,
      },
    },
  } = useResourceStore();

  const {
    permissionsDs: tableDs,
    baseInfoDs,
  } = useREStore();

  const format = useFormatMessage('c7ncd.resource');

  async function handleDelete() {
    const record = tableDs.current;
    const modalProps = {
      title: formatMessage({ id: `${intlPrefix}.permission.delete.title` }),
      children: formatMessage({ id: `${intlPrefix}.permission.delete.des` }),
      okText: formatMessage({ id: 'delete' }),
    };
    if (configTable && configTable?.destroy) {
      Modal.confirm(modalProps).then(async (button: string) => {
        if (button === 'ok') {
          try {
            const config = configTable.destroy(projectId, record?.get('id'));
            await axios(config);
            tableDs.query();
          } catch (e) {
            console.log(e);
          }
        }
      });
    } else {
      Modal.confirm(modalProps).then(async (button: string) => {
        if (button === 'ok') {
          try {
            await environmentApiApi.deleteUserByPermission(envId, record?.get('iamUserId'));
            tableDs.query();
          } catch (e) {
            console.log(e);
          }
        }
      });
      // tableDs.delete(record, modalProps);
    }
  }

  const deleteItem = {
    service: [],
    text: format({ id: 'Delete' }),
    action: handleDelete,
  };

  function renderActions({ record }: any) {
    const actionData = [
      deleteItem,
    ];
    const isOwner = !record.get('gitlabProjectOwner');
    return isOwner && <Action data={actionData} />;
  }

  function renderDate({ value }: any) {
    return value && <TimePopover content={value} />;
  }

  function renderRole({ record, text, value }: any) {
    const configAction = get('configuration.environment.permissionAssign:table');
    const roleRender = configAction?.columnRender?.roles?.renderer;
    if (roleRender) {
      return roleRender(record, value, text);
    }
    const roles = map(value || [], 'name');
    return (
      <Tooltip title={roles.join()}>
        {roles.join()}
      </Tooltip>
    );
  }

  function getActionColumn() {
    const configAction = get('configuration.environment.permissionAssign:action');
    if (configAction) {
      return configAction(deleteItem, undefined, tableDs);
    }
    const envRecord = baseInfoDs.current;
    if (!envRecord) return null;
    const isSkip = envRecord.get('skipCheckPermission');
    return !isSkip && <Column renderer={renderActions} />;
  }

  function renderRealName({ record, value, text }: any) {
    const configAction = get('configuration.environment.permissionAssign:table');
    const realNameRender = configAction?.columnRender?.realName;
    if (realNameRender) {
      return realNameRender(record, value, text);
    }
    return text;
  }

  return (
    <div className="c7ncd-tab-table">
      <Table
        dataSet={tableDs}
        border={false}
        queryBar={'bar' as TableQueryBarType}
        pristine
      >
        <Column
          name="realName"
          sortable
          renderer={renderRealName}
        />
        {' '}
        {getActionColumn()}
        <Column name="loginName" sortable />
        <Column name="roles" renderer={renderRole} />
        <Column name="creationDate" renderer={renderDate} sortable />
      </Table>
    </div>
  );
};

export default observer(Permissions);
